package com.atguigu.gmall.activity.listener;

import com.atguigu.gmall.activity.service.SeckillOrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/***
 * 订单超时消息监听器
 */
@Component
@Slf4j
public class SeckillOrderTimeoutListener {

    @Autowired
    private SeckillOrderService seckillOrderService;

    @RabbitListener(queues = "seckill_order_dead_queue")
    public void listenSeckillOrderTimeout(Channel channel, Message message){
        //获取消息对象的属性
        MessageProperties properties = message.getMessageProperties();
        //获取消息的投递标签
        long deliveryTag = properties.getDeliveryTag();

        //1 获取消息内容（用户名），并反序列化
        String username = new String(message.getBody());

        try{
            //2 执行业务层的方法，处理取消超时订单
            seckillOrderService.cancelOrder(username);

            //3 确认消息
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            //4 处理异常
            try{
                if(properties.getRedelivered()){
                    //消息确认两次都失败，直接丢弃
                    channel.basicReject(deliveryTag,false);

                    log.error("取消超时订单失败，用户名为：" + username);
                }else {
                    //消息确认第一次失败，再试一次
                    channel.basicReject(deliveryTag,true);
                }
            }catch (Exception e1){
                log.error("拒收消息时发生异常，超时订单的用户名为：" + username);
            }
        }
    }
}
